package org.example.project_12.controller;

import jakarta.servlet.http.HttpSession;
import org.example.project_12.dto.DocumentDto;
import org.example.project_12.dto.SpaceDto;
import org.example.project_12.entity.User;
import org.example.project_12.service.DocumentService;
import org.example.project_12.service.SpaceService;
import org.example.project_12.service.CommentService;
import org.example.project_12.dto.CommentDisplayDto;
import org.example.project_12.entity.Comment;
import org.example.project_12.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/document")
public class DocumentPageController {

    @Autowired
    private DocumentService documentService;

    @Autowired
    private SpaceService spaceService;

    @Autowired
    private CommentService commentService;

    @Autowired
    private UserService userService;

    /**
     * 创建文档页面
     */
    @GetMapping("/create")
    public String createDocumentPage(@RequestParam(required = false) Long spaceId, HttpSession session, Model model) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/user/login";
        }
        // 获取用户的空间列表
        List<SpaceDto> userSpaces = spaceService.getSpacesByOwnerId(user.getId());
        model.addAttribute("userSpaces", userSpaces);
        model.addAttribute("edit", false);
        model.addAttribute("user", user);
        model.addAttribute("selectedSpaceId", spaceId);
        return "documentEditor";
    }

    /**
     * 编辑文档页面
     */
    @GetMapping("/edit/{documentId}")
    public String editDocumentPage(@PathVariable Long documentId, 
                                   HttpSession session, 
                                   Model model) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/user/login";
        }

        try {
            // 获取文档详情
            DocumentDto document = documentService.getDocumentById(documentId, user.getId());
            
            // 检查编辑权限
            if (!document.getAuthorId().equals(user.getId())) {
                model.addAttribute("error", "您没有权限编辑此文档");
                return "error";
            }

            // 获取用户的空间列表
            List<SpaceDto> userSpaces = spaceService.getSpacesByOwnerId(user.getId());
            
            model.addAttribute("document", document);
            model.addAttribute("userSpaces", userSpaces);
            model.addAttribute("edit", true);
            model.addAttribute("user", user);

            return "documentEditor";
        } catch (Exception e) {
            model.addAttribute("error", e.getMessage());
            return "error";
        }
    }

    /**
     * 文档详情页面
     */
    @GetMapping("/detail/{documentId}")
    public String documentDetailPage(@PathVariable Long documentId, 
                                     HttpSession session, 
                                     Model model) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/user/login";
        }

        try {
            // 获取文档详情
            DocumentDto document = documentService.getDocumentById(documentId, user.getId());
            
            // 检查查看权限
            if (!"PUBLIC".equals(document.getStatus()) && !document.getAuthorId().equals(user.getId())) {
                // 检查是否在同一个空间且有权限
                if (document.getSpaceId() != null) {
                    // 这里需要检查用户是否是该空间的成员
                    // 暂时简化处理，实际应该调用空间服务检查权限
                } else {
                    model.addAttribute("error", "您没有权限查看此文档");
                    return "error";
                }
            }

            // 获取评论列表
            List<Comment> comments = commentService.getCommentsByDoc(documentId);
            List<CommentDisplayDto> commentDtos = new java.util.ArrayList<>();
            for (Comment c : comments) {
                if (c.getParentId() == null) {
                    CommentDisplayDto dto = toDisplayDto(c);
                    dto.setReplies(findReplies(comments, c.getId()));
                    commentDtos.add(dto);
                }
            }
            
            // 检查是否已收藏
            boolean isFavorited = documentService.isDocumentFavorited(documentId, user.getId());
            
            // 检查权限
            boolean canEdit = document.getAuthorId().equals(user.getId());
            boolean canDelete = document.getAuthorId().equals(user.getId()) || "ADMIN".equals(user.getRole());
            boolean canComment = "PUBLIC".equals(document.getStatus()) || document.getAuthorId().equals(user.getId());
            boolean canManageComments = "ADMIN".equals(user.getRole());

            model.addAttribute("document", document);
            model.addAttribute("comments", commentDtos);
            model.addAttribute("isFavorited", isFavorited);
            model.addAttribute("canEdit", canEdit);
            model.addAttribute("canDelete", canDelete);
            model.addAttribute("canComment", canComment);
            model.addAttribute("canManageComments", canManageComments);
            model.addAttribute("user", user);

            return "documentDetail";
        } catch (Exception e) {
            model.addAttribute("error", e.getMessage());
            return "error";
        }
    }

    private List<CommentDisplayDto> findReplies(List<Comment> all, Long parentId) {
        List<CommentDisplayDto> replies = new java.util.ArrayList<>();
        for (Comment c : all) {
            if (parentId.equals(c.getParentId())) {
                CommentDisplayDto dto = toDisplayDto(c);
                dto.setReplies(findReplies(all, c.getId()));
                replies.add(dto);
            }
        }
        return replies;
    }
    private CommentDisplayDto toDisplayDto(Comment c) {
        CommentDisplayDto dto = new CommentDisplayDto();
        dto.setId(c.getId());
        dto.setContent(c.getContent());
        dto.setAuthorId(c.getAuthorId());
        dto.setAuthorName(userService.getUserById(c.getAuthorId()).getUsername());
        dto.setParentId(c.getParentId());
        dto.setCreatedAt(c.getCreatedAt());
        return dto;
    }

    /**
     * 处理文档创建
     */
    @PostMapping("/create")
    public String createDocument(@RequestParam String title,
                                 @RequestParam String content,
                                 @RequestParam(required = false) Long spaceId,
                                 @RequestParam(defaultValue = "false") String isPublic,
                                 HttpSession session,
                                 Model model) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/user/login";
        }

        try {
            org.example.project_12.dto.CreateDocumentDto createDto = new org.example.project_12.dto.CreateDocumentDto();
            createDto.setTitle(title);
            createDto.setContent(content);
            createDto.setSpaceId(spaceId);
            createDto.setIsPublic("true".equals(isPublic));

            DocumentDto document = documentService.createDocument(createDto, user.getId());
            model.addAttribute("msg", "文档创建成功");
            return "redirect:/document/detail/" + document.getId();
        } catch (Exception e) {
            model.addAttribute("error", e.getMessage());
            return "redirect:/document/create";
        }
    }

    /**
     * 处理文档更新
     */
    @PostMapping("/edit/{documentId}")
    public String updateDocument(@PathVariable Long documentId,
                                 @RequestParam String title,
                                 @RequestParam String content,
                                 @RequestParam(required = false) Long spaceId,
                                 @RequestParam(defaultValue = "false") String isPublic,
                                 HttpSession session,
                                 Model model) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/user/login";
        }

        try {
            org.example.project_12.dto.UpdateDocumentDto updateDto = new org.example.project_12.dto.UpdateDocumentDto();
            updateDto.setTitle(title);
            updateDto.setContent(content);
            updateDto.setSpaceId(spaceId);
            updateDto.setIsPublic("true".equals(isPublic));

            DocumentDto document = documentService.updateDocument(documentId, updateDto, user.getId());
            model.addAttribute("msg", "文档更新成功");
            return "redirect:/document/detail/" + document.getId();
        } catch (Exception e) {
            model.addAttribute("error", e.getMessage());
            return "redirect:/document/edit/" + documentId;
        }
    }

    /**
     * 处理文档删除
     */
    @PostMapping("/delete/{documentId}")
    public String deleteDocument(@PathVariable Long documentId,
                                 HttpSession session,
                                 Model model) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/user/login";
        }

        try {
            boolean result = documentService.deleteDocument(documentId, user.getId());
            if (result) {
                model.addAttribute("msg", "文档删除成功");
            } else {
                model.addAttribute("error", "文档删除失败");
            }
        } catch (Exception e) {
            model.addAttribute("error", e.getMessage());
        }

        return "redirect:/user/docs";
    }

    /**
     * 处理文档收藏/取消收藏
     */
    @PostMapping("/favorite/{documentId}")
    public String toggleFavorite(@PathVariable Long documentId,
                                 HttpSession session,
                                 Model model) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/user/login";
        }

        try {
            boolean isFavorited = documentService.isDocumentFavorited(documentId, user.getId());
            if (isFavorited) {
                documentService.unfavoriteDocument(documentId, user.getId());
                model.addAttribute("msg", "已取消收藏");
            } else {
                documentService.favoriteDocument(documentId, user.getId());
                model.addAttribute("msg", "已添加到收藏");
            }
        } catch (Exception e) {
            model.addAttribute("error", e.getMessage());
        }

        return "redirect:/document/detail/" + documentId;
    }

    /**
     * 处理评论创建
     */
    @PostMapping("/comment/create")
    public String createComment(@RequestParam Long documentId,
                                @RequestParam String content,
                                @RequestParam(required = false) Long parentId,
                                HttpSession session,
                                Model model) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/user/login";
        }

        try {
            org.example.project_12.dto.CommentDto commentDto = new org.example.project_12.dto.CommentDto();
            commentDto.setDocId(documentId);
            commentDto.setContent(content);
            commentDto.setParentId(parentId);

            commentService.addComment(documentId, user.getId(), content, parentId);
            model.addAttribute("msg", "评论发表成功");
        } catch (Exception e) {
            model.addAttribute("error", e.getMessage());
        }

        return "redirect:/document/detail/" + documentId;
    }

    /**
     * 处理评论删除
     */
    @PostMapping("/comment/delete/{commentId}")
    public String deleteComment(@PathVariable Long commentId,
                                HttpSession session,
                                Model model) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/user/login";
        }

        try {
            // 获取评论信息以获取文档ID
            org.example.project_12.entity.Comment comment = commentService.getCommentById(commentId);
            if (comment == null) {
                model.addAttribute("error", "评论不存在");
                return "redirect:/user/docs";
            }

            boolean isAdmin = "ADMIN".equals(user.getRole());
            commentService.deleteComment(commentId, user.getId(), isAdmin);
            model.addAttribute("msg", "评论删除成功");
            
            return "redirect:/document/detail/" + comment.getDocId();
        } catch (Exception e) {
            model.addAttribute("error", e.getMessage());
            return "redirect:/user/docs";
        }
    }

    /**
     * 导出文档
     */
    @GetMapping("/export/{documentId}")
    public void exportDocument(@PathVariable Long documentId,
                               HttpSession session,
                               jakarta.servlet.http.HttpServletResponse response) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return;
        }

        try {
            String content = documentService.exportDocumentAsTxt(documentId, user.getId());
            
            // 设置响应头
            response.setContentType("text/plain;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + 
                             java.net.URLEncoder.encode("文档_" + documentId + ".txt", "UTF-8") + "\"");
            
            // 写入内容
            response.getWriter().write(content);
            response.getWriter().flush();
        } catch (Exception e) {
            // 导出失败，可以记录日志
            e.printStackTrace();
        }
    }
} 